from D5Core.Details.D5Api import D5Api
from D5Core.D5Common import D5Singleton,D5Scene
from D5Core.Details.D5Api import APIRequestType

from PySide2.QtCore import QObject, Signal

import json



class SceneToolSig(QObject):
    """
    场景工具信号类，用于在场景工具操作时发出信号。
    
    该类继承自QObject，并定义了一个信号screen_shot_sig，
    用于通知屏幕截图操作的结果。
    """
    scenes_sig: Signal = Signal(str)



@D5Singleton
class SceneTool:
    def __init__(self):
        self.scenes = {}
        self.__scenes_sig = SceneToolSig()
        self.__scenes_sig.scenes_sig.connect(self.__handle_scenes)
        pass

    def emit_scenes(self, jsonstr: str):
        """
        发出场景列表信号。
        
        :param jsonstr: 包含场景信息的JSON字符串
        :type jsonstr: str
        """
        self.__scenes_sig.scenes_sig.emit(jsonstr)

    def __handle_scenes(self, jsonstr: str):
        json_data = json.loads(jsonstr)
        scenes = json_data.get("scenes", [])
        self.scenes.clear()  # 清空现有场景列表
        for scene in scenes:
            scene_id = scene.get("sceneid", "")
            if scene_id:
                self.scenes[scene_id] = D5Scene(
                    name=scene.get("name", ""),
                    image_path=scene.get("imagepath", ""),
                    scene_id=scene_id,
                    scenecamid=scene.get("scenecamid", "")
                )
    
    def get_scenes(self):
        return self.scenes
    
    def update_scenes(self):
        """
        更新场景列表。
        
        通过D5Api获取最新的场景信息，并发出信号通知更新。
        """
        req_id = D5Api().generate_uuid()
        payload = {
            "uuid": req_id,
            "type": APIRequestType.SCENES_INFO.value,
            "content": "{}"
        }
        res = D5Api().request_sync(req_id, json.dumps(payload))
        self.emit_scenes(res)
    
    def switch_scene(self, scene_id: str):
        """
        切换到指定的场景。
        
        :param scene_id: 场景的唯一标识符
        :type scene_id: str
        :return: 切换是否成功
        :rtype: bool
        """
        req_id = D5Api().generate_uuid()
        payload = {
            "uuid": req_id,
            "type": APIRequestType.SWITCH_SCENE.value,
            "content": json.dumps({"scene_id": scene_id})
        }
        res = D5Api().request_sync(req_id, json.dumps(payload))
        res = json.loads(res)
        
        return res.get("success", False)

    def get_screen_shot(self):
        req_id = D5Api().generate_uuid()
        payload = {
            "uuid": req_id,
            "type": APIRequestType.SCREEN_SHOT.value,
            "content": "{}"
        }
        res = D5Api().request_sync(req_id, json.dumps(payload))
        res = json.loads(res)
        success = res.get("success", False)
        if success:
            res = res.get("response","")
            res = json.loads(res)
            return res.get("path", "")
        return ""
    
    

    